package com.gitee.zycra.future.job.web.handler;

import com.gitee.zycra.future.job.common.container.WebSocketSessionContainer;
import com.gitee.zycra.future.job.common.dto.NodeStatusDTO;
import com.gitee.zycra.future.job.common.util.JSONUtil;
import com.gitee.zycra.future.job.service.JobNodeService;
import com.gitee.zycra.future.job.service.JobRunningService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author zycra
 */
@Slf4j
@Component
public class JobWebSocketHandler extends TextWebSocketHandler {


    private static final String IP_KEY = "ip";

    private static final String APPLICATION_NAME_KEY = "applicationName";

    @Autowired
    private JobNodeService jobNodeService;

    @Autowired
    private JobRunningService jobRunningService;

    @Autowired
    private WebSocketSessionContainer webSocketSessionContainer;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        webSocketSessionContainer.setSession(getValueFromSession(session, APPLICATION_NAME_KEY), getValueFromSession(session, IP_KEY), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.debug("接到消息, payload={}", payload);
        NodeStatusDTO nodeStatusDTO = JSONUtil.parseObject(payload, NodeStatusDTO.class);
        jobNodeService.syncNodeStatus(nodeStatusDTO, getValueFromSession(session, APPLICATION_NAME_KEY), getValueFromSession(session, IP_KEY));
        jobRunningService.updateScheduleRatio(nodeStatusDTO.getRunningList());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        webSocketSessionContainer.removeSession(getValueFromSession(session, APPLICATION_NAME_KEY), getValueFromSession(session, IP_KEY));
    }

    private String getValueFromSession(WebSocketSession session, String key) {
        return String.valueOf(session.getAttributes().get(key));
    }
}
